package com.learn.mybatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.learn.mybatis.bean.EmpStatus;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

/**
 * 实现TypeHandler接口。或者继承BaseTypeHandler
 */
//@MappedJdbcTypes(JdbcType.VARCHAR)
//@MappedTypes(com.learn.mybatis.bean.EmpStatus.class)
public class MyEnumEmpStatusTypeHandler_2 implements TypeHandler<EmpStatus> {

    /**
     * 定义当前数据如何保存到数据库中
     * 调用原生JDBC，给SQL传参
     */
    @Override
    public void setParameter(PreparedStatement ps, int i, EmpStatus parameter, JdbcType jdbcType) throws SQLException {

        System.out.println("setParameter--要保存的状态码：" + parameter.getCode());
        ps.setString(i, parameter.getCode().toString());
    }

    /**
     * 从返回结果中，按照列名封装bean
     */
    @Override
    public EmpStatus getResult(ResultSet rs, String columnName) throws SQLException {
        // 需要根据从数据库中拿到的枚举的状态码返回一个枚举对象
        int code = rs.getInt(columnName);
        System.out.println("getResult(ResultSet rs, String columnName)--从数据库中获取的状态码：" + code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;
    }

    /**
     * 从返回的结果中，按照列的索引，封装bean
     */
    @Override
    public EmpStatus getResult(ResultSet rs, int columnIndex) throws SQLException {
        int code = rs.getInt(columnIndex);
        System.out.println("getResult(ResultSet rs, int columnIndex)--从数据库中获取的状态码：" + code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;
    }

    /**
     * 从存储过程中，按照列的索引，封装bean
     */
    @Override
    public EmpStatus getResult(CallableStatement cs, int columnIndex) throws SQLException {
        int code = cs.getInt(columnIndex);
        System.out.println("getResult(CallableStatement cs, int columnIndex)--从数据库中获取的状态码：" + code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;
    }

}
